package com.hardydou.framework.auth;

import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.hardydou.common.constant.Const;
import com.hardydou.common.utils.RegionUtil;
import com.hardydou.system.model.SystemLoginLog;
import com.hardydou.system.service.ISystemLoginLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author ：hardy
 * @description：登录验证失败
 * @date ：Created in 2020/6/6
 * @Copyright ：Hardydou.com
 */
public class AuthFailHandler extends SimpleUrlAuthenticationFailureHandler {
    @Autowired
    private ISystemLoginLogService loginLogService;

    public AuthFailHandler() {
        setDefaultFailureUrl("/login?error=true");
    }

    /**
     * Performs the redirect or forward to the {@code defaultFailureUrl} if set, otherwise
     * returns a 401 error code.
     * <p>
     * If redirecting or forwarding, {@code saveException} will be called to cache the
     * exception for use in the target view.
     *
     * @param request
     * @param response
     * @param exception
     */
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {

        UserAgent ua = UserAgentUtil.parse(request.getHeader("User-Agent"));
        SystemLoginLog loginLog = new SystemLoginLog();
        String ip = ServletUtil.getClientIP(request);
        loginLog.setLoginIp(ip);
        loginLog.setUserId(0L);
        loginLog.setLoginBrowser(ua.getBrowser().toString());
        loginLog.setUserName(request.getParameter("username"));
        loginLog.setLoginLocation(RegionUtil.getRegion(ip));
        loginLog.setLoginOs(ua.getOs().
                toString());
        loginLog.setFail(true);
        loginLog.setRemark(exception.getMessage());
        loginLogService.add(loginLog);
        super.onAuthenticationFailure(request, response, exception);
    }


}
